import COLLAPSE_ICON from '@/assets/image/collapse.png';
import CONTINUE_SM_ICON from '@/assets/image/continue_sm.png';
import COPY_ICON from '@/assets/image/copy.png';
import DEL_ICON from '@/assets/image/del_sm.png';
import DUANLUO_ICON from '@/assets/image/duanluo.png';
import ERR_ICON from '@/assets/image/error.png';
import GENE_LOADING from '@/assets/image/generate_loading.gif';
import KUOXIE_ICON from '@/assets/image/kuoxie.png';
import KUOXIE_SM_ICON from '@/assets/image/kuoxie_sm.png';
import OPEN_ICON from '@/assets/image/open.png';
import REDIAN_ICON from '@/assets/image/redian.png';
import REWRITE from '@/assets/image/rewrite.png';
import REWRITE_SM from '@/assets/image/rewrite_sm.png';
import SUOXIE_ICON from '@/assets/image/suoxie.png';
import SUOXIE_SM_ICON from '@/assets/image/suoxie_sm.png';
import YUQI_ICON from '@/assets/image/yuqi.png';
import ReferDoc from '@/components/FeferDoc';
import { HOTS } from '@/constants/index';
import { express, paragraphService, short } from '@/services/ant-design-pro/api';
import { filterResult } from '@/utils/index';
import { CheckOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { Button, Checkbox, Divider, Form, Input, InputNumber, List, message, Modal } from 'antd';
import React, { useState } from 'react';
import { styles } from './styles';

// 1:重写 2:扩写 3:缩写 4:续写 5删除 6 热点写作
const actionService = {
  1: express, // 全文编辑也有段落编辑 todo优化
  2: express,
  3: short,
  4: paragraphService,
  6: express,
};

let timer: any = null;

const Write: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [checked, setChecked] = useState(true);
  const [form] = Form.useForm();
  const [modalTitle, setModalTitle] = useState<string>('');
  const [isOpen, setIsOpen] = useState<boolean>(false);
  const [isDelOpen, setIsDelOpen] = useState<boolean>(false);
  const [actionType, setActionType] = useState<number>(2);
  const [paragraph, setParagraph] = useState<boolean>(false);
  const [hover, setHover] = useState<number>(-1);
  const [openAction, setOpenAction] = useState<boolean>(false); // 段落action是否打开
  const [num, setNum] = useState<string>('');
  const [content, setContent] = useState<string>('');
  const [requireContent, setRequireContent] = useState<string>('');
  const [paragranContent, setParagranContent] = useState<number>(-1); // 记录的是序号
  const [doc, setDoc] = useState<any>(null);
  const [referDoc, setReferDoc] = useState<string>('');
  const [collapse, setCollapse] = useState<boolean>(false);
  const [modalPosition, setModalPosition] = useState<any>({
    top: '140px',
    left: '30%',
  });
  const [showError, setShowError] = useState<boolean>(false);
  const [hot, setHot] = useState<number>();
  const [hotHover, setHotHover] = useState<number>();
  const [edit, setEdit] = useState<boolean>();
  const { TextArea } = Input;
  const onFinish = (values: any) => {
    console.log(values);
  };
  const handleOk = async () => {
    if (num <= 0) {
      setShowError(true);
      return;
    }
    if (actionType === 6) {
      form.setFieldValue('content', HOTS[hot]);
    }
    if (!form.getFieldValue('content')) {
      message.error('请输入要点');
      return;
    }
    setOpenAction(false);
    setIsOpen(false);
    setLoading(true);
    try {
      let serviceFunc = actionService[actionType];
      const contentKey = actionType === 6 ? HOTS[hot] : form.getFieldValue()?.content || '';
      setContent(contentKey);
      let params = {
        target_word_count: num || 0,
        reference: referDoc || '',
        content: contentKey,
      };
      if (paragraph) {
        serviceFunc = paragraphService;
        params = {
          target_word_count: num || 0,
          full_content: doc?.content?.join(),
          paragraph_content: doc?.content[paragranContent],
          action_type: actionType,
          require_content: requireContent,
        };
      }
      const res = await serviceFunc(params);
      if (res?.success && res?.result) {
        setLoading(false);
        if (paragraph) {
          const contenTemp = doc?.content || [];
          contenTemp[paragranContent] = res?.result;
          setDoc({
            title: '',
            content: contenTemp || [],
          });
          return;
        }
        const contentArr = filterResult(res?.result);
        setDoc({
          title: '',
          content: contentArr || [],
        });
        setCollapse(true);
      }
    } catch (err) {
      console.log(err, 'err======');
    } finally {
      setIsOpen(false);
      setLoading(false);
      setRequireContent('');
    }
  };

  const handleCancel = () => {
    setIsOpen(false);
  };

  const handleDelete = () => {
    setIsDelOpen(false);
    doc?.content?.splice(paragranContent, 1);
    setDoc({
      title: '',
      content: doc?.content || [],
    });
    if (doc?.content?.length <= 0) {
      setCollapse(false);
    }
  };

  const handleAction = (type: number, paragraph?: string, e?: any) => {
    setModalPosition({
      top: e.clientY + 30 + 'px',
      left: e.clientX - 60 + 'px',
    });
    setParagraph(!!paragraph);
    if (paragraph) {
      setParagranContent(hover);
    }
    setActionType(type);
    setShowError(false);
    if (type === 2) {
      setIsOpen(true);
      setModalTitle('扩写');
    } else if (type === 3) {
      setIsOpen(true);
      setModalTitle('缩写');
    } else if (type === 4) {
      setModalTitle('续写');
      setIsOpen(true);
    } else if (type === 1) {
      if (!paragraph) {
        setModalPosition({
          top: e.clientY + 30 + 'px',
          left: e.clientX - 280 + 'px',
        });
      }
      setIsOpen(true);
      setModalTitle('重写');
    } else if (type === 5) {
      setIsDelOpen(true);
    } else if (type === 6) {
      setIsOpen(true);
      setModalTitle('热点写作');
      setModalPosition({
        top: e.clientY + 40 + 'px',
        left: e.clientX - 280 + 'px',
      });
    } else if (type === 7) {
      setEdit(true);
    }
    setHot(-1);
    setOpenAction(false);
  };

  const handleNum = (value) => {
    setNum(value);
    setShowError(!value);
  };

  const updateReferDoc = (e) => {
    setReferDoc(e);
  };

  const handleContentKey = (e) => {
    const contentKey = e.target.value || '';
    setContent(contentKey);
  };

  // const handleMouseOut = () => {
  //   timer = setTimeout(() => {
  //     setHot(-1);
  //     setHover(-1);
  //     setOpenAction(false);
  //     setEdit(false);
  //   }, 0);
  // };

  const handleMouseHover = (index: number) => {
    clearTimeout(timer);
    setHover(index);
  };

  const handleHotMouseOut = (index: number) => {
    console.log(index);
    setHotHover(-1);
  };

  const handleHotMouseHover = (index: number) => {
    setHotHover(index);
  };

  const onCopy = () => {
    if (!doc?.content) {
      message.warning('请先生成文章');
      return;
    }
    let oInput = document.createElement('input');
    oInput.value = doc?.content?.join('\\n') || '';
    document.body.appendChild(oInput);
    oInput.select(); // 选择对象
    document.execCommand('Copy'); // 执行浏览器复制命令
    message.success('复制成功');
    oInput.remove();
  };

  const handleChangeParaEdit = (e) => {
    doc.content[paragranContent] = e.target.value || '';
    setDoc({
      title: '',
      content: doc?.content || [],
    });
  };

  return (
    <PageContainer title={false} style={{ padding: 0, margin: 0 }}>
      <div style={styles.container}>
        {/* 左边布局，参考文档、AI智能匹配文档 */}
        <div style={styles.refer}>
          <ReferDoc updateReferDoc={updateReferDoc} contentKey={content} />
        </div>
        {/* 右边布局，要点输入、扩写、续写等 */}
        <div style={styles.content}>
          <Form form={form} name="control-hooks" onFinish={onFinish}>
            {doc?.content?.length > 0 && (
              <div
                style={{ position: 'absolute', left: '25px', top: 56 }}
                onClick={() => setCollapse(!collapse)}
              >
                <img src={collapse ? OPEN_ICON : COLLAPSE_ICON} width={20} height={40} />
              </div>
            )}
            {!collapse && (
              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <Form.Item name="useRefer" rules={[]}>
                    <Button style={{ ...styles.button }}>
                      <Checkbox
                        checked={checked}
                        onChange={() => setChecked(!checked)}
                        style={{ marginTop: '2px' }}
                      >
                        根据参考文档生成
                      </Checkbox>
                    </Button>
                  </Form.Item>
                  <div style={styles.actionBox}>
                    <Button style={{ ...styles.button }} onClick={(e) => handleAction(2, '', e)}>
                      <img src={KUOXIE_ICON} style={styles.icon} />
                      扩写
                    </Button>
                    <Button style={{ ...styles.button }} onClick={(e) => handleAction(3, '', e)}>
                      <img src={SUOXIE_ICON} style={styles.icon} />
                      缩写
                    </Button>
                    <Button style={{ ...styles.button }} disabled>
                      <img src={YUQI_ICON} style={styles.icon} />
                      修改语气
                    </Button>
                    <Button style={{ ...styles.button }} onClick={(e) => handleAction(6, '', e)}>
                      <img src={REDIAN_ICON} style={styles.icon} />
                      热点写作
                    </Button>
                  </div>
                </div>
                <Form.Item
                  name="content"
                  rules={[{ required: true, message: '请输入要点' }]}
                  style={{ color: '#333', margin: '0' }}
                >
                  <TextArea
                    autoSize={true}
                    placeholder="请输入要点"
                    bordered={false}
                    style={styles.inputBox}
                    onChange={handleContentKey}
                  />
                </Form.Item>
              </div>
            )}
            {collapse && (
              <div>
                <div
                  style={{
                    color: '#C5C6CB',
                    borderBottom: '1px solid #EBEBEB',
                    paddingBottom: '10px',
                  }}
                  onClick={() => setCollapse(false)}
                >
                  <span
                    style={{
                      textOverflow: 'ellipsis',
                      overflow: 'hidden',
                      lineClamp: '2',
                      display: '-webkit-box',
                      WebkitLineClamp: '2',
                      WebkitBoxOrient: 'vertical',
                    }}
                  >
                    {form.getFieldValue()?.content || hot}
                  </span>
                </div>
                <div
                  style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: '20px' }}
                >
                  <Button style={{ ...styles.button }} onClick={onCopy}>
                    <img src={COPY_ICON} style={styles.icon} />
                    复制
                  </Button>
                  <Button
                    style={{ ...styles.button, background: '#FFFBF9', border: '1px solid #FFE6D2' }}
                    onClick={(e) => handleAction(1, '', e)}
                  >
                    <img src={REWRITE} style={styles.icon} />
                    重新生成
                  </Button>
                </div>
              </div>
            )}
          </Form>
          {loading && (
            <Modal
              footer={false}
              open={loading}
              closable={false}
              showCloseIcon={false}
              width={'335px'}
              height={'75px'}
              centered
            >
              <div style={styles.loading}>
                <img src={GENE_LOADING} alt="" height={44} width={74} />
                AI智能生成中,请稍等......
              </div>
            </Modal>
          )}
          {doc && (
            <div style={{ marginTop: '18px' }}>
              {/* <h3>{doc?.title || ''}</h3> */}
              {doc.content.map((item: string, index: number) => {
                return (
                  <div
                    key={index}
                    style={styles.box}
                    // onMouseOut={handleMouseOut}
                    onMouseOver={() => handleMouseHover(index)}
                  >
                    {hover === index && openAction && (
                      <div>
                        <div style={styles.editItem}>
                          <Button
                            disabled={true}
                            style={styles.sm_button}
                            type="text"
                            onClick={(e) => handleAction(1, 'paragraph', e)}
                          >
                            <img src={REWRITE_SM} style={styles.icon_sm} />
                            重写
                          </Button>
                          <Divider type="vertical" />
                          <Button
                            disabled={true}
                            style={styles.sm_button}
                            type="text"
                            onClick={(e) => handleAction(2, 'paragraph', e)}
                          >
                            <img src={KUOXIE_SM_ICON} style={styles.icon_sm} />
                            扩写
                          </Button>
                          <Divider type="vertical" />
                          <Button
                            disabled={true}
                            style={styles.sm_button}
                            type="text"
                            onClick={(e) => handleAction(3, 'paragraph', e)}
                          >
                            <img src={SUOXIE_SM_ICON} style={styles.icon_sm} />
                            缩写
                          </Button>
                          <Divider type="vertical" />
                          <Button
                            disabled={true}
                            style={styles.sm_button}
                            type="text"
                            onClick={(e) => handleAction(4, 'paragraph', e)}
                          >
                            <img src={CONTINUE_SM_ICON} style={styles.icon_sm} />
                            续写
                          </Button>
                          <Button
                            style={styles.sm_button}
                            type="text"
                            onClick={(e) => handleAction(5, 'paragraph', e)}
                          >
                            <img src={DEL_ICON} style={styles.icon_sm} />
                            删除
                          </Button>
                        </div>
                      </div>
                    )}
                    {hover === index && (
                      <img
                        src={DUANLUO_ICON}
                        alt=""
                        style={styles.contentItemPre}
                        onClick={() => setOpenAction(!openAction)}
                      />
                    )}
                    {hover === index ? (
                      <div
                        style={
                          openAction
                            ? { ...styles.contentItem, ...styles.hoverBg }
                            : { ...styles.contentItem }
                        }
                        onClick={(e) => handleAction(7, 'paragraph', e)}
                      >
                        {edit ? (
                          <Form.Item name="paragraph" style={{ width: '100%', marginBottom: '0' }}>
                            <TextArea
                              defaultValue={item || ''}
                              bordered={false}
                              autoSize={true}
                              style={styles.inputBox}
                              onChange={handleChangeParaEdit}
                            ></TextArea>
                          </Form.Item>
                        ) : (
                          item || ''
                        )}
                        <div style={styles.count}>{item?.length}字</div>
                      </div>
                    ) : (
                      <div
                        style={{
                          ...styles.contentItem,
                          ...(!collapse && styles.contentItemDisabled),
                        }}
                      >
                        {item || ''}
                        <div style={styles.count}>{item?.length}字</div>
                      </div>
                    )}
                  </div>
                );
              })}
              <div style={styles.allCount}>总{doc.content?.join()?.length}字</div>
            </div>
          )}
        </div>
        {/* 扩写、缩写字数输入、热点写作弹窗弹窗 */}
        <Modal
          title={paragraph ? '' : modalTitle}
          open={isOpen}
          onOk={handleOk}
          onCancel={handleCancel}
          style={{ position: 'absolute', top: modalPosition.top, left: modalPosition.left }}
          destroyOnClose
          closable={false}
          mask={false}
          width={360}
          footer={[
            <Button
              key="submit"
              type="primary"
              onClick={handleOk}
              style={{ background: '#397BFF' }}
            >
              生成
            </Button>,
          ]}
        >
          生成字数约
          <InputNumber
            min={1}
            style={{ width: '100px', margin: '8px', background: '#F9FAFF' }}
            onChange={handleNum}
          />
          字
          {showError && (
            <div style={{ color: 'red', fontSize: '14px', alignItems: 'center', display: 'flex' }}>
              <img src={ERR_ICON} width={16} style={{ marginRight: '2px' }} />
              请输入生成字数
            </div>
          )}
          {actionType === 1 && (
            <TextArea
              rows={4}
              autoSize={true}
              bordered={false}
              placeholder="请给一些重写的方向...(非必填)"
              onChange={(e) => {
                setRequireContent(e.target?.value);
              }}
              style={{ height: '100px', ...styles.inputBox, fontSize: '14px' }}
            />
          )}
          {actionType === 6 && (
            <div>
              <Divider
                style={{
                  marginLeft: '-24px',
                  marginBottom: '12px',
                  marginTop: '14px',
                  width: '360px',
                }}
              />
              <List
                itemLayout="horizontal"
                dataSource={HOTS}
                renderItem={(item, index) => (
                  <List.Item
                    style={{ color: 'blue', marginTop: '0' }}
                    onClick={() => setHot(index)}
                    onMouseOut={handleHotMouseOut}
                    onMouseOver={() => handleHotMouseHover(index)}
                  >
                    <a
                      href="javascript: void(0)"
                      style={
                        index === hot || hotHover === index
                          ? { color: '#397BFF' }
                          : { color: '#000' }
                      }
                    >
                      {item}
                    </a>
                    {index === hot && <CheckOutlined color="#397BFF" />}
                  </List.Item>
                )}
              />
            </div>
          )}
        </Modal>
        {/* 删除段落弹窗 */}
        <Modal
          title={<div style={{ display: 'flex', justifyContent: 'center' }}>确认删除</div>}
          open={isDelOpen}
          onOk={handleOk}
          mask={false}
          destroyOnClose
          centered
          closable={false}
          width={300}
          footer={[
            <div key="1" style={{ display: 'flex', justifyContent: 'center', gap: '34px' }}>
              <Button onClick={() => setIsDelOpen(false)} style={{ width: '88px', height: '32px' }}>
                取消
              </Button>
              <Button
                type="primary"
                danger
                onClick={handleDelete}
                style={{ width: '88px', height: '32px' }}
              >
                确认
              </Button>
            </div>,
          ]}
        >
          <div
            style={{
              display: 'flex',
              fontSize: '14px',
              justifyContent: 'center',
              margin: '18px 0 26px',
            }}
          >
            确认删除该段落吗?
          </div>
        </Modal>
      </div>
    </PageContainer>
  );
};

export default Write;
